package top.oneit.jdownload.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import top.oneit.jdownload.data.entity.DownloadFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author lingkang
 * @date 2021/11/13
 */
public class AddChrome95RequestHeadersInterceptor implements Interceptor {
    public AddChrome95RequestHeadersInterceptor() {
    }

    private DownloadFile downloadFile;

    public AddChrome95RequestHeadersInterceptor(DownloadFile downloadFile) {
        this.downloadFile = downloadFile;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // 添加来源
        String Referer = request.url().url().toString();
        Referer = Referer.substring(0, Referer.indexOf("/", 8)) + "/";
        // 添加默认请求头
        Headers defaultHeaders = ApplicationConfig.getDefaultHeaders(Referer);
        request = request.newBuilder().headers(defaultHeaders).build();

        if (downloadFile != null && downloadFile.getDownloadParam() != null) {
            Request.Builder builder = new Request.Builder();
            if (StrUtil.isNotBlank(downloadFile.getDownloadParam().getHeader())) {
                JSONObject parse = (JSONObject) JSON.parse(downloadFile.getDownloadParam().getHeader());
                for (Map.Entry entry : parse.entrySet()) {
                    builder.addHeader(entry.getKey().toString(), entry.getValue().toString());
                }
                request = request.newBuilder().headers(builder.build().headers()).build();
            }
        }
        return chain.proceed(request);
    }
}
